package cn.codeartist.springboot.component.util;

import javax.servlet.http.HttpServletRequest;

/**
 * Web工具类
 *
 * @author 艾江南
 * @date 2019/4/20
 */
public final class WebUtils {

    /**
     * 获取请求IP
     */
    public static String getClientIp(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        String unknown = "unknown";
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        int length = 15;
        if (ip != null && ip.length() > length) {
            String str = ",";
            if (ip.indexOf(str) > 0) {
                ip = ip.substring(0, ip.indexOf(str));
            }
        }
        return ip;
    }
}
